package com.shujia.wyh.java_moni_hadoop;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MyMap implements Runnable {
    private File file;
    private int index;
    BufferedReader br;
    BufferedWriter bw;


    public MyMap(File file, int index) {
        this.file = file;
        this.index = index;
    }

    @Override
    public void run() {
        /**
         * 统计每个block块中班级个数
         */
        try {
            br = new BufferedReader(new FileReader(file.getAbsolutePath()));
            HashMap<String, Integer> map = new HashMap<>();
            String line = null;
            while ((line = br.readLine()) != null) {
                String clazz = line.split(",")[4];
                //向集合添加元素
                if (!map.containsKey(clazz)) {
                    map.put(clazz, 1);
                } else {
                    map.put(clazz, map.get(clazz) + 1);
                }
            }

            //统计后将集合中的结果写入到文件中
            bw = new BufferedWriter(new FileWriter("bigdata23-hadoop/data/mapouts/part-m-" + index));
            //遍历集合，将每一个map任务计算的结果写入到文件中
            Set<Map.Entry<String, Integer>> entries = map.entrySet();
            for (Map.Entry<String, Integer> entry : entries) {
                String clazz = entry.getKey();
                Integer number = entry.getValue();
                bw.write(clazz+":"+number);
                bw.newLine();
                bw.flush();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
